import Vue from 'vue'
import Loading from '../components/common/Loading.vue'

const LoadingConstructor = Vue.extend(Loading)

export default {
  bind(el, binding) {
    // 设置父元素定位，以便loading可以相对定位
    const position = getComputedStyle(el).position
    if (position === 'static' || position === '') {
      el.style.position = 'relative'
    }
    
    // 确保父元素有明确的高度
    if (el.style.minHeight === '') {
      el.style.minHeight = '100px'
    }
    
    // 检查是否有开屏动画正在显示
    const splashScreenVisible = document.querySelector('.splash-screen') && 
      !document.querySelector('.splash-screen.fade-out');
      
    // 如果有开屏动画正在显示，则不显示局部加载组件
    if (splashScreenVisible) {
      return;
    }
    
    try {
      const loading = new LoadingConstructor({
        propsData: {
          local: true, // 默认使用局部加载模式
          customTexts: binding.value && binding.value.texts ? binding.value.texts : [] // 支持传入自定义文本
        }
      })
      loading.$mount()
      el.instance = loading
      el.appendChild(loading.$el)
      
      // 支持直接传入布尔值或对象形式的指令绑定值
      if (typeof binding.value === 'boolean') {
        updateVisibility(el.instance, binding.value);
      } else if (binding.value && typeof binding.value === 'object') {
        updateVisibility(el.instance, binding.value.visible !== undefined ? binding.value.visible : false);
      }
    } catch (error) {
      console.error('Error initializing loading directive:', error);
    }
  },
  
  update(el, binding) {
    // 检查元素是否有加载实例
    if (!el.instance) return;
    
    try {
      // 支持直接传入布尔值或对象形式的指令绑定值
      if (typeof binding.value !== typeof binding.oldValue) {
        if (typeof binding.value === 'boolean') {
          updateVisibility(el.instance, binding.value);
        } else if (binding.value && typeof binding.value === 'object') {
          // 更新文本（如果提供）
          if (binding.value.texts && !areArraysEqual(binding.value.texts, binding.oldValue?.texts)) {
            el.instance.$props.customTexts = binding.value.texts;
          }
          
          // 更新可见性（如果提供）
          if (binding.value.visible !== binding.oldValue?.visible) {
            updateVisibility(el.instance, binding.value.visible);
          }
        }
      } else {
        if (typeof binding.value === 'boolean' && binding.value !== binding.oldValue) {
          updateVisibility(el.instance, binding.value);
        } else if (binding.value && typeof binding.value === 'object') {
          // 对象值变化处理
          if (binding.value.visible !== binding.oldValue?.visible) {
            updateVisibility(el.instance, binding.value.visible);
          }
          
          // 更新文本（如果提供）
          if (binding.value.texts && !areArraysEqual(binding.value.texts, binding.oldValue?.texts)) {
            el.instance.$props.customTexts = binding.value.texts;
          }
        }
      }
    } catch (error) {
      console.error('Error updating loading directive:', error);
    }
  },
  
  unbind(el) {
    if (el.instance) {
      try {
        el.removeChild(el.instance.$el)
        el.instance.$destroy()
      } catch (error) {
        console.error('Error unbinding loading directive:', error);
      } finally {
        el.instance = null
      }
    }
  }
}

// 更新Loading组件的可见性
function updateVisibility(instance, isVisible) {
  if (!instance) return;
  
  // 设置组件props
  instance.$props.visible = isVisible;
  
  // 也调用实例方法以确保状态一致
  if (isVisible) {
    instance.showLoading && instance.showLoading();
  } else {
    instance.hideLoading && instance.hideLoading();
  }
}

// 辅助函数：比较两个数组是否相等
function areArraysEqual(arr1, arr2) {
  if (!arr1 || !arr2) return false;
  if (arr1.length !== arr2.length) return false;
  
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) return false;
  }
  
  return true;
} 